﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace WpfApp2
{
    public class ExcelHelper
    {
        public static void Export(DataGrid dataGrid)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Excel(2007-2016)|*.xlsx";
            saveFileDialog.ShowDialog();
            if (saveFileDialog.FileName == "")
            {
                return;//文件名为空或取消不作为
            }
            var extension = System.IO.Path.GetExtension(saveFileDialog.FileName);

            if (extension.Equals(".xlsx"))
            {
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("Sheet1");
                IRow rowHead = sheet.CreateRow(0);
                for (int i = 0; i < dataGrid.Columns.Count; i++)
                {
                    rowHead.CreateCell(i, CellType.String).SetCellValue(dataGrid.Columns[i].Header.ToString());//建立表头
                }
                var list = dataGrid.Items;
                int index = 0;
                foreach (Model item in list)
                {
                    IRow row1 = sheet.CreateRow(index + 1);
                    for (int j = 0; j < dataGrid.Columns.Count; j++)
                    {
                        var temp = dataGrid.Columns[j];
                        var model = item;
                        var p = model.GetType().GetProperty(temp.SortMemberPath);
                        if (p != null)
                        {
                            row1.CreateCell(j, CellType.String).SetCellValue(p.GetValue(model, null)?.ToString());
                        }
                        else
                        {
                            row1.CreateCell(j, CellType.String).SetCellValue("-");
                        }
                    }
                    index++;    
                }
                for (int i = 0; i < dataGrid.Items.Count; i++)
                {
                    break;
                    try
                    {
                        IRow row1 = sheet.CreateRow(i + 1);
                        for (int j = 0; j < dataGrid.Columns.Count; j++)
                        {
                            var temp = dataGrid.Columns[j];
                            var model = list[i] as Model;
                            var p = model.GetType().GetProperty(temp.SortMemberPath);
                            if (p != null)
                            {
                                row1.CreateCell(j, CellType.String).SetCellValue(p.GetValue(model, null)?.ToString());
                            }
                            else
                            {
                                row1.CreateCell(j, CellType.String).SetCellValue("-");
                            }
                        }
                        //DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);//DataGrid元素索引转换 记得开启表格不虚拟化提速，否则这里取到的为空

                        //for (int j = 0; j < dataGrid.Columns.Count; j++)
                        //{
                        //    TextBlock cellContent = dataGrid.Columns[j].GetCellContent(row) as TextBlock;//输出内容
                        //    var temp = dataGrid.Columns[j];

                        //    if (cellContent != null)
                        //    {
                        //        row1.CreateCell(j, CellType.String).SetCellValue(cellContent.Text);//填入表格
                        //    }
                        //    else
                        //    {
                        //        var model = (dataGrid.ItemsSource as List<PayHistory>)[i];
                        //        var p = model.GetType().GetProperty(temp.SortMemberPath);
                        //        if (p != null)
                        //        {
                        //            row1.CreateCell(j, CellType.String).SetCellValue(p.GetValue(model, null).ToString());
                        //        }
                        //        else
                        //        {
                        //            row1.CreateCell(j, CellType.String).SetCellValue("-");
                        //        }

                        //    }
                        //}
                    }
                    catch (Exception ex)
                    {

                        MessageBox.Show(ex.Message);
                    }

                }
                for (int i = 0; i < dataGrid.Columns.Count; i++)
                {
                    sheet.AutoSizeColumn(i);//表格格式默认自动
                }
                if (System.IO.File.Exists(saveFileDialog.FileName))
                {
                    File.Delete(saveFileDialog.FileName);
                }
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        using (FileStream stream = File.OpenWrite(saveFileDialog.FileName))
                        {
                            workbook.Write(stream);
                            stream.Close();
                        }
                    }
                    catch (Exception ex)
                    {


                        MessageBox.Show(ex.Message);

                    }

                });

                System.Windows.MessageBox.Show("导出数据成功!");
                GC.Collect();//废品回收站
                return;
            }
        }

        public static DataTable Import(DataGrid dataGrid, bool isFirstRowColumn)
        {
            OpenFileDialog saveFileDialog = new OpenFileDialog();
            saveFileDialog.Filter = "Excel(2007-2016)|*.xlsx";
            saveFileDialog.ShowDialog();
            if (saveFileDialog.FileName == "")
            {
                return null;//文件名为空或取消不作为
            }
            var extension = System.IO.Path.GetExtension(saveFileDialog.FileName);
            string sheetName = string.Empty;
            string fileName = saveFileDialog.FileName;
            if (extension.Equals(".xlsx"))
            {
                ISheet sheet = null;
                DataTable data = new DataTable();
                int startRow = 0;
                try
                {
                    var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                    var workbook = WorkbookFactory.Create(fs);
                    if (sheetName != null)
                    {
                        sheet = workbook.GetSheet(sheetName);
                        //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                        if (sheet == null)
                        {
                            sheet = workbook.GetSheetAt(0);
                        }
                    }
                    else
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                    if (sheet != null)
                    {
                        IRow firstRow = sheet.GetRow(0);
                        int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号，即总的列数
                        if (isFirstRowColumn)
                        {
                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                            {
                                ICell cell = firstRow.GetCell(i);
                                if (cell != null)
                                {
                                    string cellValue = cell.StringCellValue;
                                    if (cellValue != null)
                                    {
                                        DataColumn column = new DataColumn(cellValue);
                                        data.Columns.Add(column);
                                    }
                                }
                            }
                            startRow = sheet.FirstRowNum + 1;//得到项标题后
                        }
                        else
                        {
                            startRow = sheet.FirstRowNum;
                        }
                        //最后一列的标号
                        int rowCount = sheet.LastRowNum;
                        for (int i = startRow; i <= rowCount; ++i)
                        {
                            IRow row = sheet.GetRow(i);
                            if (row == null) continue; //没有数据的行默认是null　　　　　　　

                            DataRow dataRow = data.NewRow();
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                                    dataRow[j] = row.GetCell(j).ToString();
                            }
                            data.Rows.Add(dataRow);
                        }
                    }
                    return data;
                }
                catch (Exception ex)//打印错误信息
                {
                    MessageBox.Show("Exception: " + ex.Message);
                    return null;
                }
            }
            else
            {
                MessageBox.Show("请选择.xlsx文件");
            }

            return null;
        }
    }
}
